package com.ldatum.crm.daoImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ldatum.crm.dao.CustomerDao;
import com.ldatum.crm.domain.Customer;
import com.ldatum.crm.util.HibernateUtil;

public class CustomerDaoImpl implements CustomerDao {

	@Override
	public void add(Customer customer) throws Exception{
		HibernateUtil.add(customer);
	}

	@Override
	public void delete(Customer customer, int id) throws Exception {
		HibernateUtil.delete(customer);
	}

	@Override
	public void update(Customer customer, int id) throws Exception {
		HibernateUtil.update(customer);
	}

	@Override
	public Customer findById(Class<Customer> clazz, int id)  throws Exception{
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Customer customer = (Customer) s.get(clazz, id);
			return customer;
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public List<Customer> myCustomer(Class<Customer> clazz, String proprietor) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from Customer as customer where proprietor =:proprietor order by buildDate DESC";
			Query q = s.createQuery(hql);
			q.setString("proprietor", proprietor);
			@SuppressWarnings("unchecked")
			List<Customer> list = (List<Customer>) q.list();
			return list;
		}finally{
			s.close();
		}
	}

	@Override
	public String generateNo(String currentDate) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "select max(no) as no from Customer as customer where no like '%"+currentDate+"%'";
			Query q = s.createQuery(hql);
			String maxNo = (String) q.uniqueResult();//查找出的最大的客户编号
			String no = "";//要返回的客户编号
			if(maxNo==null){
				no = "KH"+currentDate+"001";
			}else{
				int suffix = Integer.parseInt(maxNo.substring(maxNo.length()-4, maxNo.length()));
				suffix = suffix + 1;
				no = "KH"+currentDate.substring(0, currentDate.length()-1)+suffix;
			}
			return no;
		}finally{
			s.close();
		}
	}

	@Override
	public void deletes(Customer customer, String ids) throws Exception {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			String hql = "delete from Customer as customer where id in ("+ids+")";
			Query q = s.createQuery(hql);
			q.executeUpdate();
			tx.commit();
		}finally{
			if(s!=null)
			s.close();
		}
	}

}
